<?php
namespace app\royalty\logic;

use tp5_lib\common\logic\Logic;
use tp5_lib\user\model\UserModel;
use tp5_lib\account\logic\AccountLogic;
use think\db\Query;

/**
 * 分成逻辑
 * @todo 操作比较复杂，要不要做成异步的
 * @todo 是否需要通知用户
 * @property array $setting 设置项
 */
class Royalty extends Logic
{
    public function __construct()
    {
        $path = __DIR__ . "/../setting.php";
        if(!file_exists($path)){
            throw new Exception("配置文件丢失");
        }
        $this->setting = require $path;
    }
    /**
     * 计算商户端分成
     */
    public function merchant($uid,$amount,$asso_id=0)
    {
        $user_model=new UserModel();
        if(!$user=$user_model->where(["id"=>$uid])->find()){
            $this->error="商户不存在";
            return false;
        }
        if(empty($user["referral"])){
            return [];
        }
        $royalty = $amount * $this->setting["merchant"];
        return [
            ["uid"=>$user["referral"],"amount"=>$royalty,"message"=>"商家收款分成","type"=>"royalty","asso_id"=>$asso_id],
        ];
    }
    /**
     * 计算顾客端分成
     */
    public function customer($uid,$amount,$asso_id=0)
    {
        $user_model=new UserModel();
        if(!$user=$user_model->where(["id"=>$uid])->find()){
            $this->error="顾客不存在";
            return false;
        }
        $total = $amount * $this->setting["customer"]["total"];
        $ratio = $this->setting["customer"]["ratio"];
        $result=[
            ["uid"=>$user["id"],"amount"=>$total * array_shift($ratio),"message"=>"顾客付款分成","type"=>"royalty","asso_id"=>$asso_id],
        ];
        foreach($ratio as $value){
            if(empty($user["referral"])){
                return $result;
            }
            if(!$user=$user_model->where(["id"=>$user["referral"]])->find()){
                $this->error="推荐者不存在";
                return false;
            }
            $result[]=["uid"=>$user["id"],"amount"=>$total * array_shift($ratio),"message"=>"顾客付款分成","type"=>"royalty","asso_id"=>$asso_id];
        }
        
        return $result;
    }
    public function doRoyalty($list)
    {
        $account=new AccountLogic();
        if(!$account->batch("0",$list)){
            $this->error="Account:".$account->getError();
            return false;
        }
        return true;
    }
}
